<template>
    <el-form label-suffix=":" v-loading="loading" :model="formData" :rules="editable ? formRules : {}" ref="formRef"
        label-width="130px">
        <vp-card>
            <template #header>
                <vp-label zh="基础信息" en="Basic Information" />
            </template>
            <el-row>
                <vp-col :span="4">
                    <el-form-item prop="bh">
                        <template #label><vp-label zh="记录单号" en="No." /></template>
                        <div style="display: flex;width: 100%;">
                            <div style="flex: 1;">
                                <el-input v-model="formData.bh" v-if="type == 'add'" placeholder="无需填写,由系统自动生成" v-trim
                                    disabled>
                                </el-input>
                                <span v-else>{{ formData.bh }}</span>
                            </div>
                        </div>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row>
                <vp-col :span="4">
                    <el-form-item prop="xqlb">
                        <template #label><vp-label zh="需求类别" en="Unit" /></template>
                        <VpDictSelect :lxid="404" :selectedId="formData.xqlb"
                            @dictSelected="obj => { formData.xqlb = obj; }" style="width:100%" v-if="editable">
                        </VpDictSelect>
                        <span v-else>{{ formData.xqlb }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="4">
                    <el-form-item prop="xqlylx">
                        <template #label><vp-label zh="需求来源类型" en="" /></template>
                        <el-radio-group v-if="editable" v-model="formData.xqlylx" class="radio-group">
                            <el-radio :label="10"><vp-label zh="工包" en=""></vp-label></el-radio>
                            <el-radio :label="20"><vp-label zh="工单" en=""></vp-label></el-radio>
                            <el-radio :label="30"><vp-label zh="库存预测单" en=""></vp-label></el-radio>
                        </el-radio-group>
                    </el-form-item>
                </vp-col>
                <vp-col :span="4">
                    <el-form-item prop="sjjwlJh">
                        <template #label><vp-label zh="上级件号" en="" align="left" /></template>
                        <el-input v-model="formData.sjjwlJh" maxlength="100" v-if="editable" readonly>
                            <template #append>
                                <el-button @click="handleSearchSjjwlid">
                                    <SvgIcon name="ele-Search" />
                                </el-button>
                            </template>
                        </el-input>
                        <span v-else>{{ formData.sjjwlJh }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="4">
                    <el-form-item prop="sjjwlName">
                        <template #label><vp-label zh="上级件名称" en="" align="left" /></template>
                        <span v-if="formData.sjjwlJh">中文:{{ formData.sjjwlCnName }},英文:{{ formData.sjjwlEnName }}</span>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row>
                <vp-col :span="4">
                    <el-form-item prop="jjcd">
                        <template #label><vp-label zh="紧急程度" en="" /></template>
                        <el-radio-group v-if="editable" v-model="formData.jjcd" class="radio-group">
                            <el-radio :label="10"><vp-label zh="普通" en=""></vp-label></el-radio>
                            <el-radio :label="20"><vp-label zh="加快" en=""></vp-label></el-radio>
                            <el-radio :label="30"><vp-label zh="紧急" en=""></vp-label></el-radio>
                            <el-radio :label="40"><vp-label zh="停飞" en=""></vp-label></el-radio>
                        </el-radio-group>
                        <span v-else>
                            <vp-label v-show="formData.jjcd == 10" zh="普通" en=""></vp-label>
                            <vp-label v-show="formData.jjcd == 20" zh="加快" en=""></vp-label>
                            <vp-label v-show="formData.jjcd == 30" zh="紧急" en=""></vp-label>
                            <vp-label v-show="formData.jjcd == 40" zh="停飞" en=""></vp-label>
                        </span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="4">
                    <el-form-item prop="yqdhrq">
                        <template #label><vp-label zh="要起到货期" en="" /></template>
                        <span>{{ formData.yqdhrq }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="4">
                    <el-form-item prop="acTypeList">
                        <template #label><vp-label zh="适用机型" en="" /></template>
                        <basedataModelMultAllSelect :selected="formData.acTypeList"
                            @multSelected="(data: any) => { formData.acTypeList = data }" v-if="editable"
                            class="w100" />
                        <span v-else>
                            <template v-for="(item, index) in formData.acTypeList" :key="item.id">
                                <span>{{ item }}<span v-if="index < formData.acTypeList.length - 1">,</span></span>
                            </template>
                        </span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="4">
                    <el-form-item prop="aircraftList">
                        <template #label><vp-label zh="飞机" en="" /></template>
                        <AircraftMultSelect :selected="formData.aircraftList"
                            @aircraftMultSelected="(data: any) => { formData.aircraftList = data }" v-if="editable"
                            class="w100" />
                        <span v-else>
                            <template v-for="(item, index) in formData.aircraftList" :key="item.id">
                                <span>{{ item }}<span v-if="index < formData.aircraftList.length - 1">,</span></span>
                            </template>
                        </span>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row>
                <vp-col :span="1">
                    <el-form-item prop="xqyy">
                        <template #label><vp-label zh="需求原因/故障" en="" /></template>
                        <el-input v-if="editable" type="textarea" v-model="formData.xqyy" maxlength="1000"
                            placeholder="请将需求原因、故障描述、具体影响进⾏完整、准确地描述，包括时间和地点等关键要素，如办理保留，则应写清楚保留的起⽌⽇期。" />
                        <span v-else style="white-space:pre">{{ formData.xqyy }}</span>
                    </el-form-item>
                </vp-col>
            </el-row>
        </vp-card>

        <vp-card>
            <template #header>
                <vp-label zh="需求物料" en="" />
            </template>

            <vp-vxe-table :data="formData.detailList" row-key="id" minHeight="300">
                <vxe-column type="seq" align="center" title="#" width="50" />
                <vxe-column field="jh" width="110">
                    <template #header><vp-label zh="件号/产品名" en="" /></template>
                </vxe-column>
                <vxe-column field="wllx" show-overflow width="130">
                    <template #header><vp-label zh="物料类型" en="" /></template>
                    <template #default="scope">
                        <vp-label v-if="scope.row.wllx == 10" zh="航材" en="Aircraft Material" />
                        <vp-label v-else-if="scope.row.wllx == 20" zh="化工品" en="Chemical" />
                        <vp-label v-else-if="scope.row.wllx == 30" zh="工具" en="Tool" />
                    </template>
                </vxe-column>
                <vxe-column field="zwms" show-overflow>
                    <template #header><vp-label zh="名称" en="Name" /></template>
                    <template #default="{ row }">
                        <div style="display: flex;gap: 1px;">
                            <el-tag>中:{{ row.zwms }}</el-tag>
                            <el-tag>英:{{ row.ywms }}</el-tag>
                        </div>
                    </template>
                </vxe-column>
                <vxe-column field="tdjh" width="140">
                    <template #header><vp-label zh="替代件号" en="" /></template>
                    <template #default="scope">
                        <el-form-item :prop="`detailList[${scope.rowIndex}].tdjh`" label-width="auto">
                            <el-input v-model="scope.row.tdjh" v-if="editableTable(scope.row)" readonly>
                                <template #append>
                                    <el-button @click="handleSearchTdjjh(scope.row)">
                                        <SvgIcon name="ele-Search" />
                                    </el-button>
                                </template>
                            </el-input>
                            <span v-else>{{ scope.row.tdjh }}</span>
                        </el-form-item>
                    </template>
                </vxe-column>
                <vxe-column field="bh" width="140">
                    <template #header><vp-label zh="需求数量" en="" /></template>
                    <template #default="scope">
                        <el-form-item :prop="`detailList[${scope.rowIndex}].xqsl`" :rules="formRules.xqsl"
                            label-width="auto">
                            <el-input-number v-model="scope.row.xqsl" :min="1" v-if="editableTable(scope.row)" />
                            <span v-else>{{ scope.row.xqsl }}</span>
                        </el-form-item>
                    </template>
                </vxe-column>
                <vxe-column field="jykcsl" width="120">
                    <template #header><vp-label zh="建议库存数量" en="" /></template>
                    <template #default="scope">
                        <el-form-item :prop="`detailList[${scope.rowIndex}].jykcsl`" label-width="auto">
                            <el-input-number v-model="scope.row.jykcsl" :min="1" v-if="editableTable(scope.row)" />
                            <span v-else>{{ scope.row.jykcsl }}</span>
                        </el-form-item>
                    </template>
                </vxe-column>
                <vxe-column field="bz">
                    <template #header><vp-label zh="备注" en="" /></template>
                    <template #default="scope">
                        <el-form-item :prop="`detailList[${scope.rowIndex}].bz`" label-width="auto">
                            <el-input v-model="scope.row.bz" maxlength="100" v-if="editableTable(scope.row)" />
                            <span v-else>{{ scope.row.bz }}</span>
                        </el-form-item>
                    </template>
                </vxe-column>

                <vxe-column field="cgbs"
                    v-if="type == 'acceptanceProcess4Audit' || type == 'acceptanceProcess4Approve' || type == 'view'"
                    width="140">
                    <template #header><vp-label zh="是否采购" en="" /></template>
                    <template #default="scope">
                        <el-form-item :prop="`detailList[${scope.rowIndex}].cgbs`" label-width="auto">
                            <el-checkbox v-model="scope.row.cgbs" :checked="(scope.row.cgbs === 10)" :true-label="10"
                                :false-label="20" v-if="type == 'acceptanceProcess4Audit'"></el-checkbox>
                            <span v-else>
                                <vp-label v-if="scope.row.cgbs == 10" zh="是" en="Yes" />
                                <vp-label v-else zh="否" en="No" />
                            </span>
                        </el-form-item>
                    </template>
                </vxe-column>
                <vxe-column field="cgsl"
                    v-if="type == 'acceptanceProcess4Audit' || type == 'acceptanceProcess4Approve' || type == 'view'"
                    width="140">
                    <template #header><vp-label zh="采购数量" en="" /></template>
                    <template #default="scope">
                        <template v-if="scope.row.cgbs == 10">
                            <el-form-item :prop="`detailList[${scope.rowIndex}].cgsl`" label-width="auto">
                                <el-input-number v-model="scope.row.cgsl" :min="1"
                                    v-if="type == 'acceptanceProcess4Audit'" />
                                <span v-else>{{ scope.row.cgsl }}</span>
                            </el-form-item>
                        </template>
                    </template>
                </vxe-column>
                <vxe-column field="shsm"
                    v-if="type == 'acceptanceProcess4Audit' || type == 'acceptanceProcess4Approve' || type == 'view'">
                    <template #header><vp-label zh="审核说明" en="" /></template>
                    <template #default="scope">
                        <template v-if="scope.row.cgbs == 10">
                            <el-form-item :prop="`detailList[${scope.rowIndex}].shsm`" label-width="auto">
                                <el-input v-model="scope.row.shsm" maxlength="100"
                                    v-if="type == 'acceptanceProcess4Audit'" />
                                <span v-else>{{ scope.row.shsm }}</span>
                            </el-form-item>
                        </template>
                    </template>
                </vxe-column>

                <vxe-column field="lysm">
                    <template #header><vp-label zh="件号来源" en="" /></template>
                </vxe-column>
                <vxe-column width="150">
                    <template #header><vp-label zh="件号来源附件" en="" /></template>
                    <template #default="scope">
                        <VpRowAttachment :attachmentList="scope.row.attachmentList"
                            @attachmentListEmit="scope.row.attachmentList = $event"
                            :readOnly="(!editableTable(scope.row))">
                        </VpRowAttachment>
                    </template>
                </vxe-column>
                <vxe-column field="cjryName">
                    <template #header><vp-label zh="标记" en="" /></template>
                </vxe-column>

                <vxe-column align="center" width="70" v-if="type != 'view' && type != 'acceptanceProcess4Approve'">
                    <template #header>
                        <el-popover placement="top-start">
                            <template #reference>
                                <el-button circle>
                                    <SvgIcon name="ele-Plus"></SvgIcon>
                                </el-button>
                            </template>
                            <div class="box-item-content">
                                <vp-btn type="text" v-if="type == 'add' || type == 'edit'"
                                    @click="handleAddBasedataMaterialResoursePackage()">
                                    <vp-label zh="资料包" en="" />
                                </vp-btn>
                                <el-divider style="margin: 5px 0;"></el-divider>
                                <vp-btn type="text" @click="handleAddBasedataMaterial()"
                                    v-if="(type != 'acceptanceProcess4Approve')">
                                    <vp-label zh="物料清单" en="" />
                                </vp-btn>
                            </div>
                        </el-popover>
                    </template>
                    <template #default="scope">
                        <el-button circle @click="handleDeleteDetail(scope.rowIndex)" v-if="editableTable(scope.row)">
                            <SvgIcon name="ele-Minus"></SvgIcon>
                        </el-button>
                    </template>
                </vxe-column>
            </vp-vxe-table>
        </vp-card>

        <VpFileListCard :attachmentList="formData.attachmentList" @attachmentListEmit="formData.attachmentList = $event"
            :readOnly="!(editable)">
            <template #header>
                <vp-label zh="附件" en="Attachment" />
            </template>
        </VpFileListCard>

        <!--物流清单-->
        <VpBasedataMaterialDialog ref="vpBasedataMaterialDialog"></VpBasedataMaterialDialog>

        <!--资源包-->
        <VpBasedataMaterialResoursePackageDialog ref="vpBasedataMaterialResoursePackageDialogRef" />

    </el-form>
</template>
<script setup lang="ts" name="materialDemand">
import { computed, defineAsyncComponent, ref, watch } from 'vue'
import validateUtils from '/@/utils/validateUtils';
import { addDaysToCurrentDate } from '/@/utils/formatTime';
import request from '/@/utils/request';

import VpDictSelect from '/@/components/vp/dict/VpDictSelect.vue'
import basedataModelMultAllSelect from '/@/components/vp/basedata/basedataModelMultAllSelect.vue';
import VpFileListCard from '/@/components/vp/file/VpFileListCard.vue';
import VpBasedataMaterialDialog from '/@/components/vp/basedataMaterial/VpBasedataMaterialDialog.vue';
import AircraftMultSelect from '/@/components/vp/aircraft/VpAircraftMultSelect.vue';
import VpRowAttachment from '/@/components/vp/file/VpRowAttachment.vue';
import VpBasedataMaterialResoursePackageDialog from '/@/components/vp/basedataMaterialResoursePackage/VpBasedataMaterialResoursePackageDialog.vue';

import { useUserInfo } from '/@/stores/userInfo';
import { storeToRefs } from 'pinia';
const stores = useUserInfo();
const { userInfos } = storeToRefs(stores);

const props = defineProps({
    // 页面类型
    type: {
        type: String,
        default: 'add',
    },
    // 加载状态
    loading: {
        type: Boolean,
        default: false,
    },
    // 开启验证
    enableValid: {
        type: Boolean,
        default: true,
    }
});

const formData = ref({
    id: "",
    zt: null as number | null,
    bh: "",
    sqrid: "",
    sjjwlJh: "",
    sjjwlCnName: "",
    sjjwlEnName: "",
    sqrxm: "",
    sqsj: "",
    xqlb: "",
    xqlylx: null as number | null,
    xqlyid: "",
    sjjwlid: "",
    jjcd: null as number | null,
    yqdhrq: "",
    xqyy: "",
    fjglid: null,
    attachmentList: [] as any[],
    acTypeList: [] as any[],
    aircraftList: [] as any[],
    detailList: [] as any[],
});

const formRules = {
    xqlb: [validateUtils.notNull],
    jjcd: [validateUtils.notNull],

    yqdhrq: [validateUtils.notNull],
    acTypeList: [validateUtils.notNull],
    aircraftList: [validateUtils.notNull],

    jh: [validateUtils.notNull],
    xqsl: [validateUtils.notNull, validateUtils.numValidator],


}

const initFormData = () => {
    formData.value = {
        id: "",
        zt: null as number | null,
        bh: "",
        sqrid: "",
        sjjwlJh: "",
        sjjwlCnName: "",
        sjjwlEnName: "",
        sqrxm: "",
        sqsj: "",
        xqlb: "",
        xqlylx: null as number | null,
        xqlyid: "",
        sjjwlid: "",
        jjcd: null as number | null,
        yqdhrq: "",
        xqyy: "",
        fjglid: null,
        attachmentList: [] as any[],
        acTypeList: [] as any[],
        aircraftList: [] as any[],
        detailList: [] as any[],
    }
}

const editable = computed(() => {
    return props.type === 'add' || props.type === 'edit' || props.type === 'acceptanceProcess4Review';
})

const editableTable = computed(() => {
    return (row: any) => {
        if (props.type === 'acceptanceProcess4Audit' || props.type == 'acceptanceProcess4Reedit') {
            if (row.cjrid && row.cjrid != userInfos.value.user.id) {
                return false;
            }
        } else if (props.type == 'view' || props.type == 'acceptanceProcess4Approve') {
            return false;
        }
        return true;

    }
})


const formRef = ref();

// 回显数据
const setData = (data: any) => {
    initFormData();
    formData.value = {
        ...formData.value,
        ...data,
    };
}

/**
 * 获取数据
 */
const getData = (zt: number): Promise<any> => {
    return new Promise((resolve, reject) => {
        const data = {
            ...formData.value,
            dep: null,
        }
        if (zt === 10 || !props.enableValid) {
            resolve(data);
        }
        formRef.value.validate((valid: boolean) => {
            if (valid) {
                resolve(data);
            } else {
                reject();
            }
        })
    })
}

//监听到货日期
watch(() => formData.value.jjcd, (val) => {
    let day = val == 10 ? 90 : val == 20 ? 60 : val == 30 ? 30 : val == 40 ? 15 : 0;
    formData.value.yqdhrq = addDaysToCurrentDate(day);
})


//删除行
const handleDeleteDetail = (index: number) => {
    formData.value.detailList.splice(index, 1);
}

//选择航材
const vpBasedataMaterialDialog = ref();
const handleSearchSjjwlid = () => {
    vpBasedataMaterialDialog.value.handleOpen({
        multi: false,
        wllxList: 10,
        callback: (obj: any) => {
            formData.value.sjjwlid = obj.id;
            formData.value.sjjwlJh = obj.jh;
            formData.value.sjjwlCnName = obj.zwms;
            formData.value.sjjwlEnName = obj.ywms;
        }
    })
}
//替代件号
const handleSearchTdjjh = (row: any) => {
    vpBasedataMaterialDialog.value.handleOpen({
        multi: false,
        callback: (obj: any) => {
            row.tdjh = obj.jh;
        }
    })
}

//物料清单
const handleAddBasedataMaterial = () => {
    vpBasedataMaterialDialog.value.handleOpen({
        multi: true,
        callback: (obj: any) => {
            obj.forEach((item: any) => {
                const index = formData.value.detailList.findIndex((detail: any) => detail.wlid === item.id);
                if (index === -1) {
                    formData.value.detailList.push({
                        wlid: item.id,
                        wllx: item.wllx,
                        jh: item.jh,
                        zwms: item.zwms,
                        ywms: item.ywms,
                        tdjh: item.tdjjh,
                        lysm: item.lysm,
                        jhlyfjglid: "",
                        attachmentList: []
                    })
                }
            });
        }
    })
}

//资源包
const vpBasedataMaterialResoursePackageDialogRef = ref();
const handleAddBasedataMaterialResoursePackage = () => {
    vpBasedataMaterialResoursePackageDialogRef.value.handleOpen({
        callback: (obj: any) => {
            if (obj && obj.id) {
                console.log("obj:", obj);
                request.get(`/material/resoursePackage/${obj.id}`).then((res) => {
                    console.log("res:", res);
                    res.data.detailList?.forEach((item: any) => {
                        const index = formData.value.detailList.findIndex((detail: any) => detail.wlid === item.wlid);
                        if (index === -1) {
                            formData.value.detailList.push({
                                wlid: item.wlid,
                                wllx: item.wllx,
                                jh: item.jh,
                                zwms: item.zwms,
                                ywms: item.ywms,
                                tdjh: item.tdjjh,
                                lysm: item.lysm,
                                jhlyfjglid: "",
                                attachmentList: []
                            })
                        }
                    });
                });
            }
        }
    });
}



defineExpose({
    setData,
    getData,
})
</script>

<style scoped lang="scss">
.box-item-content {
    display: flex;
    flex-direction: column;
    align-items: center;
}
</style>